﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Digitalmes.Application.Extensions;
using Digitalmes.Infrastructure.Extensions;

namespace Digitalmes.Application.FunctionalTests;

/// <summary>
/// 测试治具基类，提供必要的基础服务。
/// </summary>
public abstract class BaseTestFixture
{
    public IServiceProvider Services { get; }

    private static IServiceScopeFactory _scopeFactory = null!;

    protected BaseTestFixture()
    {
        var hostBuilder = new HostBuilder();
        hostBuilder.ConfigureAppConfiguration((_, config) =>
        {
            config.AddJsonFile("appsettings.json");
        });
      
        hostBuilder.AddApplicationSetup();
        hostBuilder.AddInfrastructureSetup();

        hostBuilder.ConfigureServices((context, services) =>
        {
            Configure(services, context.Configuration);
        });

        var host = hostBuilder.Build();
        Services = host.Services;
        _scopeFactory = Services.GetRequiredService<IServiceScopeFactory>();
    }

    protected async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
    {
        using var scope = _scopeFactory.CreateScope();
        var sender = scope.ServiceProvider.GetRequiredService<ISender>();
        return await sender.Send(request);
    }

    /// <summary>
    /// 配置服务，默认配置了 <see cref="ICurrentUser"/>。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    protected virtual void Configure(IServiceCollection services, IConfiguration configuration)
    {
        services.AddScoped<ICurrentUser, MockCurrentUser>();
    }
}
